package liming.tool.maven.tool;

import liming.tool.file.FileRW;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CmdTool {
    public static String run(String cmd) throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec(cmd);

        // 捕获标准输出和标准错误
        StringBuilder outputMessage = new StringBuilder();
        StringBuilder errorMessage = new StringBuilder();

        // 读取标准输出流的线程
        Thread outputThread = new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), FileRW.FileEncoding.AUTO.getValue()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    outputMessage.append(line).append("\n");
                }
            } catch (IOException e) {
                outputMessage.append("输出流读取异常: ").append(e.getMessage());
            }
        });

        // 读取标准错误流的线程
        Thread errorThread = new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream(), FileRW.FileEncoding.AUTO.getValue()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    errorMessage.append(line).append("\n");
                }
            } catch (IOException e) {
                errorMessage.append("错误流读取异常: ").append(e.getMessage());
            }
        });

        // 启动线程并等待完成
        outputThread.start();
        errorThread.start();
        int exitCode = process.waitFor();
        outputThread.join();
        errorThread.join();

        // 构建结果
        String output = outputMessage.toString().trim();
        String error = errorMessage.toString().trim();

        // 异常处理
        if (exitCode != 0)
            return "命令执行失败 [" + exitCode + "]:\n" +
                    "命令: " + cmd + "\n" +
                    "标准输出:\n" + output + "\n" +
                    "标准错误:\n" + error;
        return output.isEmpty() ? "执行成功（无输出）" : output;
    }
}
